package com.easylinkin.linkappapi.common.translate.config;

import java.io.IOException;
import java.util.Set;
import java.util.logging.Logger;

import com.fasterxml.jackson.core.JsonGenerationException;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.ser.impl.BeanAsArraySerializer;
import com.fasterxml.jackson.databind.ser.impl.ObjectIdWriter;
import com.fasterxml.jackson.databind.ser.std.BeanSerializerBase;
import com.easylinkin.linkappapi.common.translate.CodeTranslateorFactory;

/**
 * Jackson Bean序列化
 */
public class CodeTranslateSerializer extends BeanSerializerBase {
	private static final long serialVersionUID = 1L;

	Logger LOGGER = Logger.getLogger("BeanSerializerBase");

	protected CodeTranslateSerializer(BeanSerializerBase source) {
		super(source);
	}

	protected CodeTranslateSerializer(CodeTranslateSerializer source, ObjectIdWriter objectIdWriter) {
		super(source, objectIdWriter);
	}

	protected CodeTranslateSerializer(CodeTranslateSerializer source, Set<String> toIgnore) {
		super(source, toIgnore);
	}

	protected CodeTranslateSerializer(BeanSerializerBase src, ObjectIdWriter objectIdWriter, Object filterId) {
		super(src, objectIdWriter, filterId);
	}

	@Override
	public BeanSerializerBase withObjectIdWriter(ObjectIdWriter objectIdWriter) {
		return new CodeTranslateSerializer(this, objectIdWriter);
	}

	@Override
	public void serialize(Object bean, JsonGenerator jgen, SerializerProvider provider)
			throws IOException, JsonGenerationException {
		jgen.writeStartObject();
		serializeFields(bean, jgen, provider);
		CodeTranslateorFactory.translate(bean, (key, value) -> {
			try {
				jgen.writeStringField(key, value);
			} catch (IOException e) {
				e.printStackTrace();
			}
		});
		jgen.writeEndObject();
	}

	@Override
	protected BeanSerializerBase withIgnorals(Set<String> toIgnore) {
		return new CodeTranslateSerializer(this, toIgnore);
	}

	@Override
	protected BeanSerializerBase asArraySerializer() {
		if ((_objectIdWriter == null) && (_anyGetterWriter == null) && (_propertyFilterId == null)) {
			return new BeanAsArraySerializer(this);
		}
		// already is one, so:
		return this;
	}

	@Override
	public BeanSerializerBase withFilterId(Object filterId) {
		return new CodeTranslateSerializer(this, _objectIdWriter, filterId);
	}
}